#ifndef PORTABLE_CONSTANT_ARRAY_BUILDER_H_
#define PORTABLE_CONSTANT_ARRAY_BUILDER_H_

#include <unordered_map>
#include <vector>

#include "src/pbc/portable-bytecode-operands.h"
#include "src/pbc/portable-literals.h"
#include "src/pbc/portable-primitives.h"

namespace portable {

class Function;
class Scope;
class ConstantPool;

// Constant array entries that represent singletons.
#define SINGLETON_CONSTANT_ENTRY_TYPES(V)                                    \
  V(AsyncIteratorSymbol, async_iterator_symbol)                              \
  V(ClassFieldsSymbol, class_fields_symbol)                                  \
  V(EmptyObjectBoilerplateDescription, empty_object_boilerplate_description) \
  V(EmptyArrayBoilerplateDescription, empty_array_boilerplate_description)   \
  V(EmptyFixedArray, empty_fixed_array)                                      \
  V(IteratorSymbol, iterator_symbol)                                         \
  V(InterpreterTrampolineSymbol, interpreter_trampoline_symbol)              \
  V(NaN, nan_value)

// A helper class for constructing constant arrays.
class ConstantArrayBuilder final {
 public:
  // Capacity of the 8-bit operand slice.
  static const size_t k8BitCapacity = 1u << kBitsPerByte;

  // Capacity of the 16-bit operand slice.
  static const size_t k16BitCapacity = (1u << 2 * kBitsPerByte) - k8BitCapacity;

  // Capacity of the 32-bit operand slice.
  static const size_t k32BitCapacity =
      kMaxUInt32 - k16BitCapacity - k8BitCapacity + 1;

  explicit ConstantArrayBuilder();
  ~ConstantArrayBuilder();

  ConstantPool* ToConstantPool();

  // Returns the number of elements in the array.
  size_t size() const;

  // Insert an object into the constants array if it is not already present.
  // Returns the array index associated with the object.
  size_t Insert(Smi smi);
  size_t Insert(double number);
  size_t Insert(String str);
  size_t Insert(PortableBigInt bigint);
  size_t Insert(const Scope* scope);
  size_t Insert(TemplateObjectDescription* literal);
  size_t Insert(LiteralElement* literal);
#define INSERT_ENTRY(NAME, ...) size_t Insert##NAME();
  SINGLETON_CONSTANT_ENTRY_TYPES(INSERT_ENTRY)
#undef INSERT_ENTRY

  // Inserts an empty entry and returns the array index associated with the
  // reservation. The entry's handle value can be inserted by calling
  // SetDeferredAt().
  size_t InsertDeferred();

  // Inserts |size| consecutive empty entries and returns the array index
  // associated with the first reservation. Each entry's Smi value can be
  // inserted by calling SetJumpTableSmi().
  size_t InsertJumpTable(size_t size);

  // Sets the deferred value at |index| to |object|.
  void SetDeferredAt(size_t index, Function* func);
  void SetDeferredAt(size_t index, std::vector<String>* declarations);

  // Sets the jump table entry at |index| to |smi|. Note that |index| is the
  // constant pool index, not the switch case value.
  void SetJumpTableSmi(size_t index, Smi smi);

  // Creates a reserved entry in the constant pool and returns
  // the size of the operand that'll be required to hold the entry
  // when committed.
  OperandSize CreateReservedEntry(
      OperandSize minimum_operand_size = OperandSize::kNone);

  // Commit reserved entry and returns the constant pool index for the
  // SMI value.
  size_t CommitReservedEntry(OperandSize operand_size, Smi value);

  // Discards constant pool reservation.
  void DiscardReservedEntry(OperandSize operand_size);

 private:
  friend class ConstantPool;
  friend class PbcSerializer;

  using index_t = uint32_t;

  struct ConstantArraySlice;

  class Entry {
   private:
    friend class ConstantPool;
    friend class PbcSerializer;
    enum class Tag : uint8_t;

   public:
    explicit Entry(Smi smi)
        : ref_(static_cast<uintptr_t>(smi.value())), tag_(Tag::kSmi) {}
    explicit Entry(double number)
        : ref_(*reinterpret_cast<uintptr_t*>(&number)), tag_(Tag::kNumber) {}
    explicit Entry(String str) {
      str_ = str;
      if (std::holds_alternative<std::string>(str)) {
        tag_ = Tag::kU8String;
      } else {
        tag_ = Tag::kU16String;
      }
    }
    explicit Entry(PortableBigInt bigint)
        : bigint_(bigint), tag_(Tag::kBigInt) {}
    explicit Entry(const Scope* scope)
        : ref_(reinterpret_cast<uintptr_t>(scope)), tag_(Tag::kScope) {}
    explicit Entry(TemplateObjectDescription* literal)
        : ref_(reinterpret_cast<uintptr_t>(literal)),
          tag_(Tag::kTemplateObjectLiteral) {}
    explicit Entry(LiteralElement* literal)
        : ref_(reinterpret_cast<uintptr_t>(literal)) {
      switch (literal->get_tag()) {
        case LiteralElement::Tag::kObject:
          tag_ = Tag::kObjectLiteral;
          break;
        case LiteralElement::Tag::kArray:
          tag_ = Tag::kArrayLiteral;
          break;
        case LiteralElement::Tag::kClass:
          tag_ = Tag::kClassLiteral;
          break;
        default:
          P_UNREACHABLE();
      }
    }

    int32_t GetSmi() const {
      P_DCHECK(tag_ == Tag::kSmi);
      return static_cast<int32_t>(ref_);
    }

    double GetDouble() const {
      P_DCHECK(tag_ == Tag::kNumber);
      return *reinterpret_cast<const double*>(&ref_);
    }

#define CONSTRUCT_ENTRY(NAME, LOWER_NAME) \
  static Entry NAME() { return Entry(Tag::k##NAME); }
    SINGLETON_CONSTANT_ENTRY_TYPES(CONSTRUCT_ENTRY)
#undef CONSTRUCT_ENTRY

    static Entry Deferred() { return Entry(Tag::kDeferred); }

    static Entry Hole() { return Entry(Tag::kTheHoleValue); }

    static Entry UninitializedJumpTableSmi() {
      return Entry(Tag::kUninitializedJumpTableSmi);
    }

    bool IsDeferred() const { return tag_ == Tag::kDeferred; }

    bool IsSmi() const { return tag_ == Tag::kSmi; }

    bool IsJumpTableEntry() const {
      return tag_ == Tag::kUninitializedJumpTableSmi ||
             tag_ == Tag::kJumpTableSmi;
    }

    void SetDeferred(Function* func) {
      P_DCHECK_EQ(tag_, Tag::kDeferred);
      tag_ = Tag::kFunction;
      ref_ = reinterpret_cast<uintptr_t>(func);
    }

    void SetDeferred(std::vector<String>* declarations) {
      P_DCHECK_EQ(tag_, Tag::kDeferred);
      tag_ = Tag::kTopDeclarations;
      ref_ = reinterpret_cast<uintptr_t>(declarations);
    }

    void SetJumpTableSmi(Smi smi) {
      P_DCHECK_EQ(tag_, Tag::kUninitializedJumpTableSmi);
      tag_ = Tag::kJumpTableSmi;
      ref_ = static_cast<uintptr_t>(smi.value());
    }

    int32_t GetJumpTableSmi() const {
      P_DCHECK(tag_ == Tag::kJumpTableSmi);
      return static_cast<int32_t>(ref_);
    }

#if DEBUG
    std::string tagToStr() {
      std::string tagString[] = {
          "kDeferred",
          "kFunction",
          "kTopDeclarations",
          "kSmi",
          "kU8String",
          "kU16String",
          "kNumber",
          "kBigInt",
          "kScope",
          "kArrayLiteral",
          "kObjectLiteral",
          "kTemplateObjectLiteral",
          "kUninitializedJumpTableSmi",
          "kJumpTableSmi",
#define ENTRY_TAG(NAME, ...) "k" #NAME,
          SINGLETON_CONSTANT_ENTRY_TYPES(ENTRY_TAG)
#undef ENTRY_TAG
              "kTheHoleValue",
      };
      return tagString[static_cast<int>(tag_)];
    }

#endif

   private:
    explicit Entry(Tag tag) : tag_(tag) {}

    uintptr_t ref_;
    String str_;
    PortableBigInt bigint_;

    enum class Tag : uint8_t {
      kDeferred,
      kFunction,
      kTopDeclarations,
      kSmi,
      kU8String,
      kU16String,
      kNumber,
      kBigInt,
      kScope,
      kArrayLiteral,
      kObjectLiteral,
      kClassLiteral,
      kTemplateObjectLiteral,
      kUninitializedJumpTableSmi,
      kJumpTableSmi,
#define ENTRY_TAG(NAME, ...) k##NAME,
      SINGLETON_CONSTANT_ENTRY_TYPES(ENTRY_TAG)
#undef ENTRY_TAG
      // in constant-array-builder.cc:ToFixedArray, the constant pool will be
      // init to the_hole_value by MemsetTagged, but pbc missing this
      // initialization process
      kTheHoleValue,
    } tag_;
  };

  index_t AllocateIndex(Entry constant_entry);
  index_t AllocateIndexArray(Entry constant_entry, size_t size);
  index_t AllocateReservedEntry(Smi value);

  struct ConstantArraySlice final {
    ConstantArraySlice(size_t start_index, size_t capacity,
                       OperandSize operand_size);
    ConstantArraySlice(const ConstantArraySlice&) = delete;
    ConstantArraySlice& operator=(const ConstantArraySlice&) = delete;

    void Reserve();
    void Unreserve();
    size_t Allocate(Entry entry, size_t count = 1);
    Entry& At(size_t index);
    const Entry& At(size_t index) const;

    inline size_t available() const { return capacity() - reserved() - size(); }
    inline size_t reserved() const { return reserved_; }
    inline size_t capacity() const { return capacity_; }
    inline size_t size() const { return constants_.size(); }
    inline size_t start_index() const { return start_index_; }
    inline size_t max_index() const { return start_index_ + capacity() - 1; }
    inline OperandSize operand_size() const { return operand_size_; }

   private:
    const size_t start_index_;
    const size_t capacity_;
    size_t reserved_;
    OperandSize operand_size_;
    std::vector<Entry> constants_;
  };

  ConstantArraySlice* IndexToSlice(size_t index) const;
  ConstantArraySlice* OperandSizeToSlice(OperandSize operand_size) const;

  ConstantArraySlice* idx_slice_[3];
  std::unordered_map<std::string, index_t> bigints_map_;
  std::unordered_map<uintptr_t, index_t> scopes_map_;
  std::unordered_map<String, index_t, StringHasher, StringEqual> strings_map_;
  std::unordered_map<Smi, index_t, Smi::SmiHasher, Smi::SmiEqual> smi_map_;
  std::vector<std::pair<Smi, index_t>> smi_pairs_;
  std::unordered_map<double, index_t> heap_number_map_;

#define SINGLETON_ENTRY_FIELD(NAME, LOWER_NAME) int LOWER_NAME##_ = -1;
  SINGLETON_CONSTANT_ENTRY_TYPES(SINGLETON_ENTRY_FIELD)
#undef SINGLETON_ENTRY_FIELD
};

class ConstantPool final {
 public:
  using Tag = ConstantArrayBuilder::Entry::Tag;
  ConstantPool() : entries_() {}
  ~ConstantPool();

  bool IsSmi(int index) { return entries_[index].tag_ == Tag::kSmi; }

  Smi GetSmi(int index) {
    P_DCHECK(IsSmi(index));
    return Smi::FromInt(static_cast<int>(entries_[index].ref_));
  }

  void Set(int index, ConstantArrayBuilder::Entry entry) {
    entries_[index] = entry;
  }

  const ConstantArrayBuilder::Entry& Get(int index) const {
    return entries_[index];
  }

  uint32_t length() const { return static_cast<uint32_t>(entries_.size()); }

  void Resize(size_t size) {
    entries_.resize(size, ConstantArrayBuilder::Entry::Hole());
  }

  void Print(std::ostream& os);

 private:
  std::vector<ConstantArrayBuilder::Entry> entries_;
};

}  // namespace portable

#endif  //  PORTABLE_CONSTANT_ARRAY_BUILDER_H_
